/******************************************************************************
This file is part of AppKit.
Project: appkit
Author : FergusZeng
Email  : cblock@126.com
git	   : https://gitee.com/newgolo/appkit.git
*******************************************************************************
MIT License

Copyright (c) 2022 cblock@126.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/
#pragma once
#include <ucontext.h>

#include <map>
#include <memory>

#include "appkit/basetype.h"

/**
 * @file coroutine.h
 * @brief 协程
 */

/* Linux进程最大堆栈空间为8M-8388608Bytes(可通过"ulimit -s"查看,值单位为K) */
const int kCoroutineStackSize = 1048576; /* 1M bytes:1024*1024=1048576 */

namespace appkit {
class CoScheduler;
/**
 * @enum CoroutineState
 * @brief 协程状态
 */
enum class CoroutineState { Stop = 0, Start, Suspend };

/**
 * @class Coroutine
 * @brief 协程类
 */
class Coroutine {
    DECL_CLASSMETA(Coroutine)

public:
    Coroutine();
    virtual ~Coroutine();
    /**
     * @brief 协程运行体
     * @note 子类需实现该方法
     */
    virtual void routine() = 0;
    /**
     * @brief 获取协程ID
     * @return int
     */
    int coroutineID();
    /**
     * @brief 获取协程状态
     * @return CoroutineState
     */
    CoroutineState state();
    /**
     * @brief 微妙级休眠
     * @param us
     */
    void usleep(int us);
    /**
     * @brief 毫秒级休眠
     * @param ms
     */
    void msleep(int ms);
    /**
     * @brief 判断协程是否正在运行
     * @return true
     * @return false
     */
    bool isRunning();

protected:
    void resume();
    void yield();

private:
    void saveStack();
    void restoreStack();

private:
    friend class CoScheduler;
    CoScheduler* m_scheduler;
    int m_id;
    ucontext_t m_context;
    CoroutineState m_state{CoroutineState::Stop};
    int m_stackSize{0};
    std::unique_ptr<char[]> m_stackBuffer;
};

/**
 * @class CoScheduler
 * @brief 协程调度器
 */
class CoScheduler {
    DECL_CLASSMETA(CoScheduler)

public:
    CoScheduler();
    virtual ~CoScheduler();
    /**
     * @brief 启动协程
     * @param coroutine
     * @return true
     * @return false
     */
    bool start(std::shared_ptr<Coroutine> coroutine);
    /**
     * @brief 调度协程
     * @param coroutineID
     */
    void schedule(int coroutineID);
    /**
     * @brief 停止协程
     * @param coroutineID
     */
    void stop(int coroutineID);
    /**
     * @brief 查询当前协程个数
     * @return int
     */
    int routines();
    /**
     * @brief 返回协程上下文
     * @return void*
     */
    void* context();
    /**
     * @brief 返回协程堆栈空间
     * @return char*
     */
    char* stack();

private:
    static void coroutineEntry(void* coroutine);

private:
    std::map<int, std::shared_ptr<Coroutine>> m_coroutineMap;
    ucontext_t m_context;
    char m_stack[kCoroutineStackSize];
};

}  // namespace appkit
